package com.hup.utils.swing.customView.colorChooser;

import com.hup.utils.commons.start.LookThemeUtil;
import lombok.extern.log4j.Log4j2;

import java.awt.*;
import java.awt.image.MemoryImageSource;

/**
 * [透明度]色板
 * @author hugan
 * @date 2020/4/10
 */
@Log4j2
public class TransparencyLabel extends AbsColorLabel {

    public TransparencyLabel() {
        Dimension dimension = new Dimension(-1, (int) (25 * LookThemeUtil.getScreenScale()));
        setPreferredSize(dimension);
        setMinimumSize(dimension);
    }

    @Override
    protected int[] initPix() {
        return new int[256];
    }

    @Override
    protected boolean needUpdateImage(Color newer, Color older) {
        return image == null || newer.getRed() != older.getRed() || newer.getGreen() != older.getGreen()
                || newer.getBlue() != older.getBlue();
    }

    @Override
    protected Image updateImageByColor() {
        log.debug("");
        int r = color.getRed();
        int g = color.getGreen();
        int b = color.getBlue();
        for (int i = 0; i < pix.length; i++) {
            pix[i] = i << 24 | r << 16 | g << 8 | b;
        }
        return createImage(new MemoryImageSource(pix.length, 1, pix, 0, pix.length));
    }

    @Override
    public boolean doPaintGraphics(Graphics g) {
        g.drawImage(image, 0, 0, width, height, null);

        // 三角形游标:使用两种颜色画出游标,解决不同颜色下,顶点都可以被看到的问题
        /*
        每个色度占的横坐标像素
        如果空间很宽,则一个色度会占n个像素,鼠标拖拽时这个宽度内不会变色),所以'三角形'的顶点是平的
         */
        double perStepWid = width / (pix.length + 0d);
        int curX = (int) (color.getAlpha() * perStepWid);//顶点的x
        int h2 = height / 4;
        log.debug("width={}, perStepWid={}, curX={}", width, perStepWid, curX);

        //多边形,添加坐标时要按 顺序(顺/逆时针)添加
        Polygon p = new Polygon();//倒三角
        g.setColor(CURSOR_COLOR_C1);
        p.addPoint(curX - h2, 0);//左
        p.addPoint((int) (curX + h2 + perStepWid), 0);//右
        p.addPoint((int) (curX + perStepWid), height / 6 * 2);//右底点
        p.addPoint(curX, height / 6 * 2);//左底点
        g.fillPolygon(p);

        p.reset();
        g.setColor(CURSOR_COLOR_C2);
        p.addPoint((int) (curX + perStepWid), height / 6 * 4);//右顶点
        p.addPoint(curX, height / 6 * 4);//左顶点
        p.addPoint(curX - h2, height);//左
        p.addPoint((int) (curX + h2 + perStepWid), height);//右
        g.fillPolygon(p);
        return true;
    }

    @Override
    protected Color getMouseColor(boolean isPress, int x, int y) {
        int curI = getMxIndex(x);
        Color res = new Color(pix[curI], true);
        log.debug("x={}, y={}, curI={}, c={}, alpha={}", x, y, curI, res, res.getAlpha());
        return res;
    }
}
